<script lang='ts'>
import { defineComponent, h, onBeforeMount, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import tableMode from './components/tableMode.vue'
import pictureMode from './components/PictureMode.vue'
import filesServiceApi from '/@/api/org/bean/files'
import { downloadFile } from '/@/api/org/file-attachment'
export default defineComponent({
    name: 'JxtechAttachment'
})
</script>
<script lang='ts' setup>
//emit  对外事件
//props 对外属性
const props = defineProps({
    height: {
        type: Number
    },
    //可能是电站
    projectid: {
        type: [String, Number],
        required: true
    },
    //业务id
    busiId: {
        type: [String, Number],
        require: true
    },
    //组件id
    compId: {
        type: [String, Number],
        required: true
    },
    //附件类型
    itemType: {
        type: [String, Number],
        required: true
    },
})
//ref 
const attachementTabBtnRef = ref()
const AttachmentManageTableRef = ref()
const AttachementTableModeRef = ref()
const pictureModeRef = ref()

type QueryParams = {
    projectid: string,
    filecategory: string,
    businessid: string,
    businesstype: string,
    delflag: number,
    isRoot?: boolean | undefined,
    parentid?: string | null | undefined,
}
const AttachmentManageState = reactive({
    uploadDialogVisible: false,
    // 切换视图按钮
    pictureModeActive: true,
    inputValue: '',
    queryParams: {
        /**分页参数 一页几行 */
        rows: 25,
        /**分页参数 第几页*/
        page: 1,
        /**项目编号 */
        projectid: props.projectid,
        /**分页参数 对应上传compId */
        filecategory: props.compId,
        /**业务id 对应上传busiId*/
        businessid: props.busiId,
        /**业务类型 对应上传 itemType */
        businesstype: props.itemType,
        /**是否删除 默认给0*/
        delflag: 0,
        /**是否为root目录 有可能存在不同的子文件夹*/
        isRoot: true,
        /**如果进入子文件夹需要携带这个参数 */
        parentid: undefined
    } as QueryParams,
    // 切换到列表模式
    onLiebiaoBtnClick: (event: any) => {
        AttachmentManageState.pictureModeActive = false
    },
    // 切换到图片模式
    onTupianBtnClick: (e?: any) => {
        AttachmentManageState.pictureModeActive = true
    },
    // 新增按钮
    onNewFile: () => {
        AttachmentManageState.pictureModeActive = true
        pictureModeRef.value.pictureModeState.addNewFileShow = true
        pictureModeRef.value.pictureModeState.inputFocus()
    },
    // 上传成功
    uploadSuccess: async (_response: any, _file: any, _fileList: any) => {
        let params: { businessid: string | number | undefined; businesstype: string | number; filecategory: string | number; projectid: string | number; typeid: string | null | undefined; uuid: any }[] = []
        await _response.forEach((item: { fileId: any }) => {
            let bean = {
                businessid: props.busiId,
                businesstype: props.itemType,
                filecategory: props.compId,
                projectid: props.projectid,
                typeid: AttachmentManageState.queryParams.parentid,
                uuid: item.fileId
            }
            params.push(bean)
        })
        filesServiceApi.saveMulti({ insert: params })

    },
    // 上传按钮
    onUpload: () => {
        AttachmentManageState.uploadDialogVisible = true
    },
    // 下载按钮
    onDownload: () => {
        let allPictureModeFilelist = pictureModeRef.value.pictureModeState.filesList
        if (allPictureModeFilelist.length > 0) {
            const selectedList = allPictureModeFilelist.filter((item: any) => item.selected === true)
            if (selectedList.length > 0) {
                selectedList.forEach((item: any) => {
                    downloadFile(item.uuid).then((res) => {
                        const data = res.data
                        const a = document.createElement('a')
                        const url = window.URL.createObjectURL(new Blob([data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }))
                        const link = document.createElement('a')
                        link.style.display = 'none'
                        link.href = url
                        link.setAttribute('download', item.fileName)
                        document.body.appendChild(link)
                        link.click()
                        document.body.removeChild(link)
                    })
                })
            } else {
                ElMessage({ message: '请选择要下载的文件', type: 'warning', })
            }
        } else {
            ElMessage({ message: '当前无可以选择的文件', type: 'warning', })
        }
    },
    //删除按钮
    onDelete: () => {
        let allPictureModeFilelist = pictureModeRef.value.pictureModeState.filesList
        if (allPictureModeFilelist.length > 0) {
            const selectedList = allPictureModeFilelist.filter((item: any) => item.selected === true)
            let params: any = []
            if (selectedList.length > 0) {
                const num = selectedList.length
                ElMessageBox.confirm(
                    `确定要删除${num}个文件？`,
                    '提示：',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(() => {
                    selectedList.forEach((item: any) => {
                        let bean = { uuid: '', ftype: '' }
                        bean.uuid = item.uuid
                        bean.ftype = item.ftype
                        params.push(bean)
                        filesServiceApi.delFiles(params).then(() => {
                            ElMessage({ message: `删除成功:${item.fileName}`, type: 'success', })
                            syncTwoModeData()
                        }).catch((err) => {
                            ElMessage({ message: `删除失败：${item.fileName}`, type: 'error', })
                        }).finally(() => {
                        })
                    })
                })
            } else {
                ElMessage({
                    message: '未选择文件',
                    type: 'warning',
                })
            }
        } else {
            ElMessage({
                message: '当前无可以选择的文件',
                type: 'warning',
            })
        }
    }

})
// 刷新两个模式数据
const syncTwoModeData = () => {
    if (pictureModeRef.value && AttachementTableModeRef.value) {
        pictureModeRef.value.pictureModeState.reloadData()
        AttachementTableModeRef.value.getAttachmentTableRef().loadTable()
    }
}

// 页面导航条
type breadcrumbItems = {
    uuid?: String,
}
const AttachmentBreadcrumb = ref([]) as any
const breadcrumbChange = (breadcrumbItem: any) => {
    AttachmentBreadcrumb.value.push(breadcrumbItem)
}
const firstBreadcrumbClick = () => {
    pictureModeRef.value.pictureModeState.queryParams.isRoot = true
    AttachmentManageState.queryParams.isRoot = true
    pictureModeRef.value.pictureModeState.queryParams.parentid = undefined
    AttachmentManageState.queryParams.parentid = undefined

    syncTwoModeData()
    AttachmentBreadcrumb.value = []
}
const onBreadcrumbGo = (item: any) => {
    const idex = AttachmentBreadcrumb.value.findIndex((breadcrumbItem: breadcrumbItems) => {
        return breadcrumbItem.uuid === item.uuid
    })
    AttachmentBreadcrumb.value.splice(idex)
    pictureModeRef.value.pictureModeState.fileDblclick(item)
}
// 上传对话框关闭触发
watch(() => AttachmentManageState.uploadDialogVisible, (newval, oldval) => {
    if (newval === false && oldval === true) {
        // 刷新数据
        syncTwoModeData()
    }
})
//是否将必填属性均以设置
const flag = (props.projectid == null || props.busiId == null || props.compId == null || props.itemType == null)
onBeforeMount(() => {
    if (flag) {
        ElNotification({
            title: '注意：附件管理组件缺少必要参数',
            message: h('span', { style: 'color: red' }, 'itemType || busiId || compId || projectid'),
            duration: 0,
        })
    }
})
onMounted(() => {
    syncTwoModeData()
})
const parentidEmit = (val: any) => {
    AttachmentManageState.queryParams.parentid = val
}
const onRootChange = (isRoot: boolean | undefined) => {
    AttachmentManageState.queryParams.isRoot = isRoot
}

</script>
<template>
    <div v-if="!flag">
        <jxtech-upload-dialog
            v-model:visible="AttachmentManageState.uploadDialogVisible"
            :itemType="props.itemType"
            :busiId="props.busiId"
            :compId="props.compId"
            :projectid="props.projectid"
            :parentid="AttachmentManageState.queryParams.parentid"
            @btn-close="syncTwoModeData"
            @upload-success="AttachmentManageState.uploadSuccess"
        >></jxtech-upload-dialog>
        <div class="attachement-container">
            <div class="attachement-header">
                <h3 class="title">附件管理</h3>
                <div class="attachement-handle">
                    <div class="attachement-input-box">
                        <el-input
                            v-model="AttachmentManageState.inputValue"
                            placeholder="搜索我的文件"
                            class="input-with-select"
                        >
                            <template #append>
                                <div class="pointer">
                                    <jxtech-svg-icon :size="15" icon="#icon-search"></jxtech-svg-icon>&nbsp;查询
                                </div>
                            </template>
                        </el-input>
                    </div>
                    <!-- 按钮组 -->
                    <div class="attachement-btn-box">
                        <jxtech-add-button @click="AttachmentManageState.onNewFile"></jxtech-add-button>
                        <Jxtech-upload-button @click="AttachmentManageState.onUpload"></Jxtech-upload-button>
                        <jxtech-download-button @click="AttachmentManageState.onDownload"></jxtech-download-button>
                        <jxtech-delete-button @click="AttachmentManageState.onDelete"></jxtech-delete-button>
                    </div>
                </div>
            </div>
            <!--导航条 展示按钮 -->
            <div class="attachement-tab">
                <div>
                    <span class="as-link" @click="firstBreadcrumbClick">图片列表</span>
                    <span
                        class="as-link"
                        v-for="(item) in AttachmentBreadcrumb"
                        :key="item.uuid"
                        @click="onBreadcrumbGo(item)"
                    >&nbsp;>&nbsp;{{ item.fileName }}</span>
                </div>

                <div ref="attachementTabBtnRef">
                    <jxtech-svg-icon
                        :size="22"
                        icon="#icon-dasuolvetuliebiao"
                        class="pointer attachement-tab-btn"
                        :class="{ 'is-active-btn': AttachmentManageState.pictureModeActive }"
                        @click="AttachmentManageState.onTupianBtnClick"
                    ></jxtech-svg-icon>
                    <jxtech-svg-icon
                        :size="22"
                        icon="#icon-liebiao"
                        class="pointer attachement-tab-btn"
                        :class="{ 'is-active-btn': !AttachmentManageState.pictureModeActive }"
                        @click="AttachmentManageState.onLiebiaoBtnClick"
                    ></jxtech-svg-icon>
                </div>
            </div>
            <!-- 图片展示区 -->
            <div
                class="attachement-picture-container"
                ref="AttachmentManagePictureRef"
                v-show="AttachmentManageState.pictureModeActive"
            >
                <picture-mode
                    ref="pictureModeRef"
                    :queryParams="AttachmentManageState.queryParams"
                    :height="props.height"
                    @parentid="parentidEmit"
                    @breadcrumb="breadcrumbChange"
                    @is-root="onRootChange"
                    @sync-table-data="syncTwoModeData"
                ></picture-mode>
            </div>
            <!-- 表格展示区 -->
            <div
                class="attachement-table-container"
                ref="AttachmentManageTableRef"
                v-show="!AttachmentManageState.pictureModeActive"
            >
                <table-mode
                    ref="AttachementTableModeRef"
                    :query-params="AttachmentManageState.queryParams"
                    :compId="props.compId"
                    :height="props.height"
                ></table-mode>
            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.attachement-container {
    background-color: #fff;
    width: 100%;
    height: 100%;
    .attachement-header {
        width: 100%;
        height: 60px;
        border-bottom: 1px solid #ccc;
        display: flex;
        justify-content: space-between;
        align-items: center;
        h3 {
            padding-left: 10px;
        }
        .attachement-handle {
            display: flex;
            text-align: center;
            .attachement-input-box {
                width: 300px;
                margin-right: 20px;
            }
            .attachement-btn-box {
                width: 370px;
                display: flex;
                align-items: center;
                // justify-content: space-around;
                ::v-deep(.el-button) {
                    flex-shrink: 0;
                }
            }
        }
    }
    .attachement-tab {
        padding: 0 10px;
        height: 40px;
        line-height: 40px;
        width: 100%;
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #ccc;
        .attachement-tab-btn {
            width: 40px;
            color: #000;
            &:active {
                transform: scale(0.9);
                color: rgb(0, 104, 240);
            }
        }
    }
    .attachement-table-container {
        // height: 540px;
        opacity: 1;
        overflow: hidden;
        transition: all 0.2s;
    }
    .attachement-picture-container {
        // height: 540px;
        opacity: 1;
        overflow: auto;
        transition: all 0.2s;
    }
    .is-active-btn {
        color: rgb(0, 104, 240) !important;
    }
    .is-picture-mode-show {
        height: 0 !important;
        opacity: 0 !important;
        overflow: hidden !important;
    }
}
</style>